package 二叉树;

import java.util.ArrayList;
import java.util.List;

public class LC_257二叉树的所有路径 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res=new ArrayList<>();
        if(root==null) return res;
        List<Integer> path=new ArrayList<>();
        travel(root,res,path);
        return res;
    }
    public void travel(TreeNode root,List<String> res,List<Integer> path){
        //前序遍历
        //中
        path.add(root.val);
        if(root.left==null && root.right==null){
            StringBuilder sb=new StringBuilder();
            for(int i=0;i<path.size()-1;i++){
                sb.append(path.get(i)).append("->");
            }
            sb.append(path.get(path.size()-1));//记录最后一个结点
            res.add(sb.toString());
            return;
        }
        //左
        if(root.left!=null){
            travel(root.left,res,path);
            path.remove(path.size()-1);//回溯
        }
        //右
        if(root.right!=null){
            travel(root.right,res,path);
            path.remove(path.size()-1);//回溯
        }
    }
}
